package com.bookmanger.common.intercepter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.bookmanger.common.utils.LoginHolder;
import com.bookmanger.common.utils.ManagerHolder;
import com.bookmanger.common.utils.RedisConstants;
import com.bookmanger.common.utils.UserIdThreadLocal;
import com.bookmanger.entity.dto.LoginDTO;
import com.bookmanger.entity.dto.ManagerDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 刷新小程序用户token
 *
 * @author huangfuhao
 * @Date 2024/11/17
 */
@Slf4j
public class UserRefreshTokenInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;

    public UserRefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //  1.获取请求头中的token
        String token = request.getHeader("Authorization");

        log.info("刷新用户token拦截器" + token);
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //  2.基于token获取redis中的用户
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        String userId = stringRedisTemplate.opsForValue().get(tokenKey);
        //  3.判断用户是否存在
        if (userId == null) {
            return true;
        }
        //  4.判断是否是用户
        String[] split = userId.split("_");
        if (!split[1].equals("user")) {
            response.setStatus(-201);
            //  拦截
            return false;
        }
        //  5.将查询到的Hash数据转为UserDTO对象
//        LoginDTO loginDTO = BeanUtil.fillBeanWithMap(userMap, new LoginDTO(), false);

        //  6.存在，保存用户信息到 ThreadLocal，只存用户id
//        LoginHolder.saveUser(loginDTO);
        UserIdThreadLocal.saveUserId(Long.parseLong(split[0]));
        //  7.刷新token有效期

        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //  8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

